package com.cskaoyan.converter;

import lombok.SneakyThrows;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class String2DateConverter implements Converter<String, Date> {

    //什么情况下会调用convert方法执行类型转换
    //请求参数名和handler方法的形参名一致，类型又匹配为Converter接口这里的类型
    @SneakyThrows
    @Override
    public Date convert(String s) {
        Date date = null;
        //业务逻辑自定义
        String pattern1 = "yyyy-MM-dd";
        String pattern2 = "yyyy-MM-dd HH:mm:ss";
        String pattern3 = "yyyy-MM-dd HH:mm";
        if (s.length() == pattern1.length()){
            date = new SimpleDateFormat(pattern1).parse(s);
        }else if (s.length() == pattern2.length()){
            date = new SimpleDateFormat(pattern2).parse(s);
        } else if (s.length() == pattern3.length()) {
            date = new SimpleDateFormat(pattern3).parse(s);
        }
        return date;
    }
}
